//
//  EpointScheduleViewController.m
//  EpointFrame5
//
//  Created by 李亚春 on 14-1-27.
//  Copyright (c) 2014年 Epoint. All rights reserved.
//

#import "EpointScheduleViewController.h"
#import "PGCalendarView.h"
#import "PGCalendarItem.h"
#import "Schedule_GetList_Task.h"
#import "ScheduleInfo.h"
#import "EpointDateUtils.h"
#import "ScheduleEditViewContrllerViewController.h"
#import "UIPopoverListView.h"
#import "UIView+Addtions.h"

#define ScheduleGetListTaskId 1
#define ScheduleDelTaskId 2

@interface EpointScheduleViewController () <PGCalendarViewDelegate, UITabBarDelegate, UIPopoverListViewDelegate>

@property (nonatomic, strong) PGCalendarView *calendarView;
@property (nonatomic, strong) UIButton *backBtnItem;

@end

@implementation EpointScheduleViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self addTabBar];
    [self showMBPHUD];
    [NSThread detachNewThreadSelector:@selector(initCalendarViewAndData) toTarget:self withObject:nil];
}

-(void)homeToDetail{
    
    if (XAppDelegate.clickItemPos!=-1) {
        [self editCalendarItem:(ScheduleInfo*)XAppDelegate.clickScheduleAtHome];
    }
}

- (void)backBtnItemPressed {
    NSLog(@"123");
    [_calendarView showContainerView];
}

- (void)initCalendarViewAndData {
    [self addCalendarView];
    dispatch_sync(dispatch_get_main_queue(), ^{
        [self finishInitCalendarView];
    });
}

- (void)addTabBar {
    UITabBar *tabBar = [[UITabBar alloc] initWithFrame:CGRectMake(0, AppHeight-SystemTakeHeight-BottomBarHeight, AppWidth, BottomBarHeight)];
    tabBar.delegate = self;

    UITabBarItem *sendItem = [[UITabBarItem alloc] initWithTitle:@"今天" image:[UIImage imageNamed:@"nav_ic_jin"] tag:1];
    
    UITabBarItem *deleteItem = [[UITabBarItem alloc] initWithTitle:@"增加" image:[UIImage imageNamed:@"fun_ic_add"] tag:2];
    
    UITabBarItem *moreItem = [[UITabBarItem alloc] initWithTitle:@"选择" image:[UIImage imageNamed:@"fun_ic_search"] tag:3];
    NSArray *items = @[sendItem, deleteItem, moreItem];
    [tabBar setItems:items];
    [self.view addSubview:tabBar];
}

- (void)addCalendarView {
    
    CGRect rect = CGRectMake(0, 0, AppWidth, AppHeight-SystemTakeHeight-BottomBarHeight);
    self.calendarView = [[PGCalendarView alloc] initWithFrame:rect];
    _calendarView.delegate = self;
    [self.view addSubview:_calendarView];
}

#pragma mark - PGCalendarViewDelegate

- (void)currentMonthChanged:(PGCalendarView *)calendar {
    [self getData];
}

- (void)middleViewChanged:(CalendarOrTable)calendarOrTable {
    if (calendarOrTable == Calendar) {
        [self addCustomeBackButtonItemWithSelector:@selector(popBack)];
    } else {
        [self addCustomeBackButtonItemWithSelector:@selector(backBtnItemPressed)];
    }
}

- (void)editCalendarItem:(ScheduleInfo *)scheduleInfo {
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:scheduleInfo forKey:@"scheduleInfo"];
    ScheduleEditViewContrllerViewController *editCtrl = [[ScheduleEditViewContrllerViewController alloc] initWithParams:params];
    editCtrl.parentCtrl = self;
    [self.navigationController pushViewController:editCtrl animated:YES];
}
- (void)delCalendarItem:(ScheduleInfo *)scheduleInfo {
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:scheduleInfo.ActivityID forKey:@"ActivityID"];
    [self startTask:@"Schedule_Delete_Task" withParams:params withTaskId:ScheduleDelTaskId];
}

- (void)finishInitCalendarView {
    [self hideMBPHUD];
    [self getData];
    [self homeToDetail];
}

#pragma mark - getData

- (void)getData {
    [self showMBPHUD];
    NSString *yearAndMonth = [_calendarView getCurrentYearAndMonth];
    
    NSString *FromDateTime = [NSString stringWithFormat:@"%@-%@", yearAndMonth, @"01"];
    NSString *ToDateTime = [NSString stringWithFormat:@"%@-%d", yearAndMonth, [_calendarView getDayNumOfCurrentMonth]];

    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:FromDateTime forKey:@"FromDateTime"];
    [params setObject:ToDateTime forKey:@"ToDateTime"];
    [params setObject:@"" forKey:@"KeyWord"];
    [self startTask:@"Schedule_GetList_Task" withParams:params withTaskId:ScheduleGetListTaskId];
}


#pragma mark - 

- (void)refreshUIWithThreadGuid:(int)taskId andData:(NSObject *)obj {
    [self hideMBPHUD];
    //处理异常信息
    NSMutableArray *arr = (NSMutableArray*)obj;
    if (![[arr objectAtIndex:0]isEqualToString:@"1"]) {
        [self toastMessage:[arr objectAtIndex:1]];
        return;
    }
    
    if (taskId == ScheduleGetListTaskId) {
        NSLog(@"array:%@", [arr lastObject]);
        NSArray *tempArr = [arr lastObject];
        [self addDataToCalendarView:tempArr];
    }else if(taskId == ScheduleDelTaskId){
        [self getData];
    }
}

- (void)addDataToCalendarView:(NSArray *)tempArr {

    for (ScheduleInfo *schedule in tempArr) {
        NSLog(@"%@", schedule.FromDateTime);
        NSString *monthKey = [EpointDateUtils convertStr2FromStr:schedule.FromDateTime oldFormat:@"yyyy-MM-dd HH:mm" withNewFormat:@"yyyy-M"];
        NSString *monthToKey = [EpointDateUtils convertStr2FromStr:schedule.ToDateTime oldFormat:@"yyyy-MM-dd HH:mm" withNewFormat:@"yyyy-M"];
        [self addSchedule:schedule withMonthKey:monthKey];
        
        if (![monthKey isEqualToString:monthToKey]) {
            [self addSchedule:schedule withMonthKey:monthToKey];
        }
    }
    [_calendarView dataLoadFinish];
}
    
- (void)addSchedule:(ScheduleInfo *)schedule withMonthKey:(NSString *)monthKey {
    NSMutableArray *monthArr = [_calendarView.dataDic valueForKey:monthKey];
    if (!monthArr) {
        monthArr = [NSMutableArray array];
        [_calendarView.dataDic setObject:monthArr forKey:monthKey];
        [monthArr addObject:schedule];
    } else {
        BOOL isFound = NO;
        for (ScheduleInfo *oldSchedule in monthArr) {
            if ([oldSchedule.ActivityID isEqualToString:schedule.ActivityID]) {
                isFound = YES;
                [oldSchedule updateInfoWith:schedule];
                break;
            }
        }
        if (isFound == NO) {
            [monthArr addObject:schedule];
        }
    }
}

#pragma mark - UITabBarDelegate

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    switch (item.tag) {
        case 1:
            [self backToToday];
            break;
        case 2:
            [self addNewSchedule];
            break;
        case 3:
            [self selectSomeDate];
            break;
        default:
            break;
    }
}

- (void)backToToday {
    NSLog(@"backToToday");
    [self showMBPHUD];
    [_calendarView resetWithToday];
}

- (void)addNewSchedule {
    NSLog(@"addNewSchedule");
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    PGCalendarItem *item = [_calendarView getSelectedItem];
    if (item) {
        [params setObject:item.itemDate forKey:@"itemDate"];
    }
    ScheduleEditViewContrllerViewController *editCtrl = [[ScheduleEditViewContrllerViewController alloc] initWithParams:params];
    editCtrl.parentCtrl = self;
    [self.navigationController pushViewController:editCtrl animated:YES];
}

- (void)selectSomeDate {
    NSLog(@"selectSomeDate");
    
    CGFloat pWidth = AppWidth - 60;
    CGFloat pHeight = TitleHeight + 200;
    CGFloat pTop = (AppHeight - SystemTakeHeight - BottomBarHeight - pHeight)*0.5;
    
    UIPopoverListView *popoverList = [[UIPopoverListView alloc] initWithFrame:CGRectMake(30, pTop, pWidth, pHeight) withStyle:DatePickerStyle];
    popoverList.delegate = self;
    [popoverList setPickerDate:[_calendarView getCurrentYeartMonthAndDay]];
    [popoverList show];
}

#pragma mark - UIPopoverListViewDelegate

- (void)selectDateAt:(NSDate *)date {
    NSLog(@"selectDateAt:%@", date);
    [self showMBPHUD];
    [_calendarView resetWithDate:date];
}

@end
